package com.learn.core.controller.manager;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.learn.common.annotation.Log;
import com.learn.common.annotation.UserLoginToken;
import com.learn.common.enums.BusinessType;
import com.learn.common.enums.OperatorType;
import com.learn.common.enums.ResultEnum;
import com.learn.common.utils.JwtUtil;
import com.learn.common.utils.PageResult;
import com.learn.common.utils.ResultUtil;
import com.learn.common.utils.StringUtils;
import com.learn.common.utils.result.CommonResult;
import com.learn.core.domain.LExamSort;
import com.learn.core.domain.LOrganization;
import com.learn.core.dto.LExamSortDTO;
import com.learn.core.service.ILExamSortService;
import com.learn.core.service.ILOrganizationService;
import com.learn.framework.web.controller.WebController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Description
 *
 * @author zhaohongyu
 * @ClassName LQuestionsController
 * @date 2021.03.22 11:06
 * @describe 考试分类
 */
@Api("考试分类")
@RestController
@RequestMapping("/manager/esort")
public class LExamSortController extends WebController<LExamSort> {

    @Autowired
    private ILExamSortService ilExamSortService;
    @Autowired
    private ILOrganizationService ilOrganizationService;

    //考试分类
    @ApiOperation(value = "考试分类树")
    @UserLoginToken
    @GetMapping("/tree")
    public CommonResult<Object> tree(@RequestParam(value = "id") String id){
        try {
            QueryWrapper<LExamSort> queryWrapper = new QueryWrapper<LExamSort>();
            queryWrapper.eq("state","1");
//            queryWrapper.eq("parent_node",id).or().eq("exam_sort_id",id);
            List<LExamSort> lExamSorts = ilExamSortService.queryLExamSortAll(queryWrapper);
            if(lExamSorts.size()>0)
                return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,lExamSorts);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
    }

    //列表
    @ApiOperation(value = "获取列表")
    @UserLoginToken
    @PostMapping("/list")
    public PageResult<LExamSort> list(@RequestBody LExamSortDTO lExamSortDTO){
        try {
            if (lExamSortDTO==null||lExamSortDTO.getPage()==null||lExamSortDTO.getRows()==null){
                return new PageResult<>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lExamSortDTO.getPage(),lExamSortDTO.getRows());
            QueryWrapper<LExamSort> queryWrapper = new QueryWrapper<LExamSort>();
            if(lExamSortDTO.getParentNode()!=null)
                queryWrapper.eq("parent_node",lExamSortDTO.getParentNode());
            else {
                queryWrapper.eq("parent_node","0");
            }
            if(lExamSortDTO.getExamSortName()!=null)
                queryWrapper.like("exam_sort_name",lExamSortDTO.getExamSortName());
            if(lExamSortDTO.getState()!=null)
                queryWrapper.eq("state",lExamSortDTO.getState());
            Page<LExamSort> lExamSorts = (Page<LExamSort>) ilExamSortService.list(queryWrapper);
            if (CollectionUtils.isEmpty(lExamSorts)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            for (LExamSort lExamSort: lExamSorts) {
                LOrganization lOrganization = ilOrganizationService.getById(lExamSort.getOrganizationId());
                if(null != lOrganization)
                    lExamSort.setOrganizationName(lOrganization.getOrganizationName());
            }
            // 返回
            return new PageResult(lExamSorts.getTotal(), lExamSorts, ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }


    //新增
    @ApiOperation(value = "添加")
    @PostMapping("/add")
    @UserLoginToken
    @Log(title = "添加考试分类", businessType = BusinessType.INSERT, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> add(@RequestBody LExamSort lExamSort, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if(lExamSort!=null) {
                if (StringUtils.isEmpty(lExamSort.getExamSortName())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_EXAM_SORT_NAME);
                }
                if (StringUtils.isEmpty(lExamSort.getState())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_EXAM_SORT_STATE);
                }
                if (StringUtils.isEmpty(lExamSort.getParentNode())) {
                    lExamSort.setParentNode(0);
                }
                lExamSort.setCreateTime(new Date());
                lExamSort.setCreateUser(userId);
                if (ilExamSortService.save(lExamSort)) {
                    return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS);
                }
            }
        }catch (Exception e){
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return  (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }


    //删除
    @ApiOperation(value = "删除")
    @PostMapping("/del")
    @UserLoginToken
    @Log(title = "删除考试分类", businessType = BusinessType.DELETE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> del(@RequestBody LExamSort lExamSort){
        try {
            if(lExamSort!=null){
                if(lExamSort.getExamSortId()!=null){
                    List<Integer> ids = new ArrayList<>();
                    ids.add(lExamSort.getExamSortId());
                    if(nodeStr(ids)){
                        return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
                    }
                }
            }
        }catch (Exception e)
        {
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }

    private Boolean nodeStr (List<Integer> lists) throws Exception{
        List<Integer> ids = new ArrayList<>();
        QueryWrapper<LExamSort> queryWrapper = new QueryWrapper<LExamSort>();
        for (int i = 0; i <lists.size() ; i++) {
            int orgid = lists.get(i);

            queryWrapper.eq("parent_node",orgid);
            List<LExamSort> lExamSorts = ilExamSortService.list(queryWrapper);
            for (int j = 0; j < lExamSorts.size(); j++) {
                LExamSort lExamSort = lExamSorts.get(j);
                ids.add(lExamSort.getExamSortId());
            }
        }
        if(ids.size() > 0){
            this.nodeStr(ids);
        }

        ids.addAll(lists);
        queryWrapper = new QueryWrapper<LExamSort>();
        queryWrapper.in(true, "exam_sort_id", ids);
        ilExamSortService.remove(queryWrapper);

        return Boolean.TRUE;
    }

    //更新
    @ApiOperation(value = "更新")
    @PostMapping("/edit")
    @UserLoginToken
    @Log(title = "更新考试分类", businessType = BusinessType.UPDATE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> edit(@RequestBody LExamSort lExamSort, HttpServletRequest request) {
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        if(lExamSort!=null){
            lExamSort.setUpdateTime(new Date());
            lExamSort.setUpdateUser(userId);
            if(ilExamSortService.updateById(lExamSort)){
                return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
            }
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }
}
